package com.example.SOPVersionChain;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@SpringBootApplication
public class SopVersionChainApplication {

    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(SopVersionChainApplication.class, args);
    }
    
    @Component
    public static class DirectoryInitializer {
        
        @Value("${version.file.directory}")
        private String versionDirectory;
        
        @EventListener
        public void onApplicationEvent(ContextRefreshedEvent event) {
            try {
                System.out.println("初始化系统...");
                System.out.println("检查目录: " + versionDirectory);
                
                // 使用Path API处理跨平台路径
                Path path = Paths.get(versionDirectory);
                boolean exists = Files.exists(path);
                System.out.println("目录是否存在: " + exists);
                
                if (!exists) {
                    // 在Linux环境下创建目录
                    try {
                        Files.createDirectories(path);
                        System.out.println("创建目录成功: " + path.toString());
                    } catch (Exception e) {
                        System.err.println("创建目录失败, 可能需要管理员权限: " + e.getMessage());
                        e.printStackTrace();
                    }
                }
                
                // 检查是否可访问
                File dir = path.toFile();
                System.out.println("目录是否可读: " + Files.isReadable(path));
                System.out.println("目录是否可写: " + Files.isWritable(path));
                
            } catch (Exception e) {
                System.err.println("初始化目录时出错: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }
}
